<?php

namespace App\Http\Controllers\Api;

use App\V3\Api\Services\ShelfService;
use App\Services\StorageService;
use  App\V3\V3_1\Models\StorageModel;
use Illuminate\Http\Request;
use Validator;

class StorageController extends BaseController
{
    /**
     * @仓库列表
     * created 在 2021/10/18 16:33 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function storageList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        if($this->getUserId() == $this->getMainUserId()) {
            $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            if($this->isShareStorage()) {
                $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
            }
            else {
                $userId['a.user_id'] = ['EQ' => $this->getUserId()];
            }
        }
        return $this->success(
            StorageService::storageList(
                $userId,
                [
                    'pageSize' => $request->input('pageSize'),
                    'currentPage' => $request->input('currentPage'),
                ]
            )
        );
    }

    /**
     * @仓库列表-下拉
     * created 在 2021/10/19 16:47 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function storageSelect()
    { if($this->getUserId() == $this->getMainUserId()) {
            $userId['main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            if($this->isShareStorage()) {
                $userId['main_id'] = ['EQ' => $this->getMainUserId()];
            }
            else {
                $userId['user_id'] = ['EQ' => $this->getUserId()];
            }
        }
        return $this->success(
            StorageService::storageSelect(
                $userId
            )
        );
    }

    /**
     * @新建仓库
     * created 在 2021/10/20 11:02 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        if(empty($result = SELF::checkInfo($data = $request->all()))) {
            if(empty($data['storage_address'])) $data['storage_address'] = "";
            if(empty($data['user_id'])) $data['user_id'] = 0;
            if($this->getUserTpye()) {//子账户添加仓库
                $arr = [
                    'storage_name' => $data['storage_name'],
                    'storage_address' => $data['storage_address'],
                    'remarks' => empty($data['remarks'])?'':$data['remarks'],
                    'user_id' => $this->getUserId(),
                    'main_id' => $this->getMainUserId(),
                    'created_at' => time(),
                ];
            }
            else {//主账号添加仓库
                $arr = [
                    'storage_name' => $data['storage_name'],
                    'storage_address' => $data['storage_address'],
                    'remarks' => empty($data['remarks'])?'':$data['remarks'],
                    'user_id' => $data['user_id'],
                    'main_id' => $this->getMainUserId(),
                    'created_at' => time(),
                ];
            }

            $checkStorage = StorageModel::where([
                                            'storage_name' => $arr['storage_name'],
                                            'storage_address' => $arr['storage_address'],
                                            'main_id' => $arr['main_id'],
                                        ])
                                        ->where('delete_flag', 0)
                                        ->first();

            if(!empty($checkStorage)) {
                return $this->fail('', '仓库`'.$arr['storage_name'].'-'.$arr['storage_address'].'`已存在');
            }

            $insertId = StorageModel::insertGetId($arr);

            //添加货架和库位
            ShelfService::create_default_shelf_location($insertId,$arr['main_id']);

            $this->log('添加仓库',$arr);

            return $this->success($insertId);
        }
        else {
            return $result;
        }
    }

    /**
     * @删除指定仓库
     * created 在 2021/10/20 14:09 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request)
    {
        //验证
        $validator = Validator::make($data = $request->all(), [
                'id' =>'required|integer',//供应商客户表主键id
            ],
            [
                'id.required' => '参数`id`丢失',
            ]
        );
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $judging_status = ShelfService::judging_del($data['id'],1,$this->getMainUserId());

        if(empty($judging_status)){
            return $this->fail('','此仓库还有库存商品，不能删除');
        }

        $result = StorageService::delete($data);

        if($result['code']) {
            return $this->fail('',$result['msg']);
        }
        else {
            $this->log('删除仓库',$data);
            return $this->success();
        }
    }

    /**
     * @修改指定仓库
     * created 在 2021/10/20 14:09 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        //验证
        $validator = Validator::make($data = $request->all(), [
                'id' =>'required|integer',//供应商客户表主键id
            ],
            [
                'id.required' => '参数`id`丢失',
            ]
        );
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        if(empty($data['storage_address'])) $data['storage_address'] = "";
        if(empty(SELF::checkInfo($data = $request->all()))) {
            if(empty($data['user_id'])) $data['user_id'] = 0;
            if($this->getUserTpye()) {//子账户添加仓库
                $arr = [
                    'storage_name' => $data['storage_name'],
                    'storage_address' => $data['storage_address'],
                    'remarks' => empty($data['remarks'])?'':$data['remarks'],
                    'user_id' => $this->getUserId(),
                ];
            }
            else {//主账号添加仓库
                $arr = [
                    'storage_name' => $data['storage_name'],
                    'storage_address' => $data['storage_address'],
                    'remarks' => empty($data['remarks'])?'':$data['remarks'],
                    'user_id' => $data['user_id'],
                ];
            }
            $isUpdate = StorageModel::where('id', $data['id'])
                                    ->lockForUpdate()
                                    ->update($arr);

            if($isUpdate !== false) {
                $this->log('修改仓库信息', array_merge($arr, $data));
                return $this->success(array_merge($arr, $data));
            }
        }
        else {
            return SELF::checkInfo($request->all());
        }
    }

    private function checkInfo($data)
    {

        //参数验证
        $validator = Validator::make(
            $data,
            [
                'storage_name' =>'required',//仓库名

                /* 'user_id' =>'required',//仓库负责人id */
            ],
            [
                'storage_name.required' => '请填写仓库名称',

                /* 'user_id.required' => '请选择仓库负责人', */
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
    }
}
